package edu.washington.cs.pomdb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
/**
 * @author Yanping Huang
 *
 */
public class UserSet {
	HashSet<String> users;

	public UserSet(){
		users = new HashSet<String>();
		File userdb = new File("user.db");
		if(!userdb.exists()){
			try {
				PrintWriter out = new PrintWriter(
						new FileWriter(userdb.getAbsoluteFile()));
				out.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			BufferedReader in= new BufferedReader(
					new FileReader(userdb.getAbsoluteFile()));
			try {
				String s;
				while((s = in.readLine()) != null) {
					users.add(s);	
					File f = new File( s + ".txt");
					if(!f.exists()){
						try {
							PrintWriter out = new PrintWriter(
									new FileWriter(f.getAbsoluteFile()));
							out.close();
						} catch (FileNotFoundException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			} finally {
				in.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	public void saveFile(){
		try {
			PrintWriter out = new PrintWriter(
					new File("user.db").getAbsoluteFile());
			out.print(this);
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}

	public boolean findByName(String name){
		return users.contains(name);
	}

	public boolean register(String name){
		if(findByName(name)){
			return false;
		}
		else{
			users.add(name);
			return true;
		}		
	}
	public String toString(){
		StringBuilder sb = new StringBuilder();
		for(Object s : users.toArray()){
			sb.append(s+"\n");
		}
		return sb.toString();
	}

}
